var element,form,table,laydate,layer,colorpicker,slider;
var includeGoodsData = [
        {name:'牛肉',price:5,unit:'斤'},
        {name:'猪肉',price:5,unit:'斤'},
        {name:'花菜',price:5,unit:'斤'},
        {name:'青菜',price:5,unit:'斤'}
    ];
var includeGoodsCols = [[
    {field:'name',title:'商品名称',align:'center'},
    {field:'price',title:'原价',align:'center'},
    {field:'unit',title:'单位',align:'center'},
    {field:'',title:'操作',align:'center',templet:'#includeGoodsBtn'}
]];
// 奖励优惠券 表格数据
var discountCouponData = [
    {couponName:'八折券',indate:'2020-12-12',includeCount:'3'},
    {couponName:'七折券',indate:'2020-12-12',includeCount:'3'},
    {couponName:'六折券',indate:'2020-12-12',includeCount:'3'},
];
var discountCouponCols = [[
    {field:'couponName',align:'center',title:'券名称'},
    {field:'indate',align:'center',title:'有效期'},
    {field:'',align:'center',title:'包含张数',templet:'#discountCouponIndate'},
    {field:'',align:'center',title:'操作',templet:'#discountCouponOperate'}
]]
// 领取者领取礼包优惠券的数据
var memberCouponData = [
    {couponName:'八折券',indate:'2020-12-12',includeCount:'3'},
    {couponName:'七折券',indate:'2020-12-12',includeCount:'3'},
    {couponName:'六折券',indate:'2020-12-12',includeCount:'3'},
];
var memberCouponCols = [[
    {field:'couponName',align:'center',title:'券名称'},
    {field:'indate',align:'center',title:'有效期'},
    {field:'',align:'center',title:'包含张数',templet:'#discountCouponIndate'},
    {field:'',align:'center',title:'操作',templet:'#discountCouponOperate'}
]];
// 保存用户群体设置选择的id
var memberGroupUserId;
var sureMemberGroupUserId;
layui.use(['jquery','element','form','table','laydate','layer','colorpicker','slider'],function(){
    element = layui.element;
    table = layui.table;
    form = layui.form;
    laydate = layui.laydate;
    layer = layui.layer;
    colorpicker = layui.colorpicker;
    slider = layui.slider;
    // 监听群体设置
    form.on('radio(share-group-set)',function(r){
        if(r.value == 1){
            $("#member_grade").hide(300);
            $("#member_group").hide(300);
        }else if(r.value == 2){
            $("#member_grade").show(300);
            $("#member_group").hide(300);
        }else if(r.value == 3){
            $("#member_grade").hide(300);
            $("#member_group").show(300);
        }
    })
    // 周期循环监听
    form.on('radio(loop-set)',function(r){
        var origin = ['.use-mouth-loop','.use-week-loop'];
        controlShow(origin,'.'+r.value);
    })
    //初始化时先调用一次，确保静态的那一行可点
     timeAdd();
     // 分享领取礼包条件  奖励礼包礼品设置
     form.on('checkbox(gift-bag-set-filter)',function(r){
         console.log(r.elem.value,r.elem.checked);
         var s = '.show-'+r.elem.value+'-js';
         if(r.elem.checked){
             $(s).show(100,function(){
                renderTable({
                    elem:'#settingWrapTable',
                    data:discountCouponData,
                    cols:discountCouponCols
                })
             })
         }else{
             $(s).hide(100)
         }
     })
     // 领取礼包条件  奖励礼包礼品设置
     form.on('checkbox(get-gift-bag-filter)',function(r){
        console.log(r.elem.value,r.elem.checked);
        var s = '.show-get-gift-'+r.elem.value+'-js';
        if(r.elem.checked){
            $(s).show(100,function(){
                if(r.elem.value == 'coupon'){
                    renderTable({
                        elem:'#menberDicountCoupon',
                        data:memberCouponData,
                        cols:memberCouponCols
                    })
                 }  
            })         
        }else{
            $(s).hide(100)
        }
    })
    // 监听添加会员群体按钮
    $("#add-member-group-js").click(function(){
        layer.open({
            type:1,
            content:$("#addMemberGroupTemplate").html(),
            skin:'cancel-and-sure',
            area:['50%','80%'],
            btn:['取消','确定'],
            btnAlign:'c',
            success:function(lay,index){
                // 将数据注入到弹出框中
                let arr = [
                    {title:'A群体',conditions:['会员等级（等级1、等级2、等级3）','会员等级（等级1、等级2、等级3）'],id:1},
                    {title:'B群体',conditions:['会员等级（等级1、等级2、等级3）','会员等级（等级1、等级2、等级3）'],id:2},
                    {title:'C群体',conditions:['会员等级（等级1、等级2、等级3）','会员等级（等级1、等级2、等级3）'],id:3},
                    {title:'B群体',conditions:['会员等级（等级1、等级2、等级3）','会员等级（等级1、等级2、等级3）'],id:4},
                    {title:'C群体',conditions:['会员等级（等级1、等级2、等级3）','会员等级（等级1、等级2、等级3）'],id:5},
                    {title:'B群体',conditions:['会员等级（等级1、等级2、等级3）','会员等级（等级1、等级2、等级3）'],id:6},
                    {title:'C群体',conditions:['会员等级（等级1、等级2、等级3）','会员等级（等级1、等级2、等级3）'],id:7},
                    {title:'D群体',conditions:['会员等级（等级1、等级2、等级3）','会员等级（等级1、等级2、等级3）'],id:8}
                ];
                // 需要默认选中的id
                let defaultCheckedId = sureMemberGroupUserId;
                arr.forEach(item=>{
                    let str = `<div id="addMemberGroupWrap" data-title="${item.title}" data-id="${item.id}" class="add-member-group-wrap  ${item.id == defaultCheckedId ? 'active' : ''}">
                                 <div class="add-member-group-item">`
                    str += "<p>"+item.title+"</p>";
                    item.conditions.forEach(i => {
                        str += "<p>"+i+"</p>";
                    })
                    str += "</div></div>";
                    $(".member-popup-wrap").append(str);
                })
                // 绑定点击事件
                $(".add-member-group-wrap").click(function(){
                    $(this).addClass('active').siblings().removeClass('active');
                    memberGroupUserId = $(this).data("id");
                })
            },
            btn2:function(index,lay){
                // 当点确定时
                sureMemberGroupUserId = memberGroupUserId;
                $("#add-member-group-js").hide();
                $("#memberGroupTextWrap").html($(".add-member-group-wrap.active").data('title')+'<i id="memberGroupClose" class="layui-icon">&#x1006;</i>').show();
            }
        })
    })
    // 会员群体的删除按钮
    $(document).on('click','#memberGroupClose',function(){
        sureMemberGroupUserId = '';
        $("#memberGroupTextWrap").html('').hide();
        $("#add-member-group-js").show();
    })
    //监听添加商品按钮
    $(document).on('click','.add-goods-btn-js',function(){
        // 打开添加商品的弹出层
        layer.open({
            type:2,
            content:'./selectGoods.html',
            skin:'cancel-and-sure',
            area:['80%','80%'],
            btn:['取消','确定'],
            btnAlign:'c',
            success:function(lay,index){
                var obj = lay.find("iframe")[0].contentWindow;
                // 给弹出层传参,不过在弹出层中要在异步方法中才能获取到
                obj.parentParameter = '要传给弹出层的数据';
            },
            btn2:function(index,lay){
                console.log('确定',index)
                var obj = lay.find("iframe")[0].contentWindow;
                var data = obj.userSelectData;
                includeGoodsData = includeGoodsData.concat(data);
                // 得到新数据后重新渲染表格
                renderTable({
                    elem:'#includeGoods',
                    data:includeGoodsData,
                    cols:includeGoodsCols
                })
            }
        })
    })
    // 点击左边变 右边相应的出现配置
    $(".show-ui-item-click").click(function(){
        $(".show-or-hide-share").css('display','none');
        var index = $(this).data('index');
        $(".show-ui-item-click").removeClass('active');
        $(this).addClass('active');
        $(".control"+index).css('display','block');
    })
    // 监听所有输入框
    $(document).on('change','input.layui-input',function(){
        let id = $(this).attr('id');
        addUserOperation(id,$(this).val());
        operationFun(id,$(this).val());
    })
    //ui配置初始化
    setTimeout(function(){
        // 异步请求数据，假设setAllDatas和getAllDatas是返回的数据转换后的配置对象
        // 赋值 用来做恢复默认时用
        setAllData = setAllDatas;
        getAllData = getAllDatas;
        // 初始化ui 配置
        setAllConfig(setAllData); //分享方
        setAllConfig(getAllData); // 领取方
        // 初始化 操作记录对象 当保存数据时也要从这里提取最新的信息
        userOperationRecord = initRecord(setAllDatas);
        getOperationRecord = initRecord(getAllDatas);
    },100)

    // 开始时间和结束时间
    laydate.render({
        elem:'#begin-date-time',
        type:'datetime'
    })
    laydate.render({
        elem:'#end-date-time',
        type:'datetime'
    })
})
// 富文本编辑器初始化
KindEditor.ready(function(K) {
    window.editor = K.create('#activity_activity_rule_html',{
        resizeType : 0,
        filterMode : true,
        allowPreviewEmoticons : false,
        allowImageUpload : false,
        items : [
            'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
            'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
            'insertunorderedlist'],
        afterBlur:function(r){
            // 失去焦点就添加一条记录
            addUserOperation('activity_activity_rule_html',editor.html());
            $("#activity_activityto_rule_html").html(editor.html());
        }
    });
 });
 KindEditor.ready(function(K) {
    window.getEditor = K.create('#activityto_activityto_rule_html',{
        resizeType : 0,
        filterMode : true,
        allowPreviewEmoticons : false,
        allowImageUpload : false,
        items : [
            'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
            'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
            'insertunorderedlist'],
        afterBlur:function(r){
            // 失去焦点就添加一条记录
            addUserOperation('activityto_activityto_rule_html',getEditor.html());
            $("#activityto_activityto_rule_html_target").html(getEditor.html());
        }
    });
 });

// 初始化数据
var setAllData,getAllData;
// 记录用户操作的值改变的数据
var userOperationRecord,getOperationRecord;
// 分享方配置操作记录操作改变的键值对
var userOperation = [];
var userOperationArr = ['my_','friend_','invite_','activity_','bottom_'];
// 领取方配置操作记录
var getOperation = [];
var getOperationArr = ['you_','activityto_','bottomto_'];
// 用户操作记录初始化
function initRecord(data){
    let res = {};
    for(let key in data){
        res[key] = [data[key]];
    }
    return res;
}
// 添加操作记录
function addUserOperation(id,val){
    let o = {};
    o[id] = val;
    // 根据前缀的不同，判断是分享方配置操作还是领取方配置操作
    let suffix = id.slice(0,id.indexOf('_')+1);
    if(userOperationArr.indexOf(suffix) !== -1){
        userOperation.push(o);
        userOperationRecord[id].push(val)
    }else if(getOperationArr.indexOf(suffix) !== -1){
        getOperation.push(o);
        getOperationRecord[id].push(val);
    }
}
// 从操作记录中提取出保存项
function extractData(data){
    let res = {};
    for(let key in data){
        // 提取每一项的最后一个值
        res[key] = data[key][data[key].length-1];
    }
    return res;
}
// 将数据注入到后端需要的数据格式中
function leaveData(data,target){
    // 去除数据前缀
    for(let key in data){
        let noPreKey = key.slice(key.indexOf('_')+1);
        target[noPreKey] = data[key];
    }
}
// 分享方恢复默认
$("#setRestoreSefault").click(function(){
    setAllConfig(setAllData);
    // 操作记录也恢复默认
    userOperationRecord = initRecord(setAllData);
})
// 分享方撤销操作
$("#setOperationBack").click(function(){
    if(userOperation.length === 0){
        layer.msg('已经是最初的样子了');
        return false;
    }
    let item = userOperation.pop();
    let o = {};
    for(let key in item){
        o[key] = userOperationRecord[key][userOperationRecord[key].length-2];
        // 将记录的最后一项推出
        initForm(key,o[key]);
        userOperationRecord[key].pop();
    }
    setAllConfig(o);
})
// 分享方 保存操作(注意这个保存仅保存当前的ui配置)
$("#setSave").click(function(){
    // 从记录中提取最新的用户选择项
    let res = extractData(userOperationRecord);
    // 将数据转成后端需要的格式
    let changeRes = {
        share_ui_set:{
            my_coupon_list:{

            }
        }
    }
    leaveData(res,changeRes.share_ui_set.my_coupon_list);
    console.log(changeRes);
})
// 领取方恢复默认
$("#getRestoreSefault").click(function(){
    setAllConfig(getAllData);
    // 操作记录也恢复默认
    getOperationRecord = initRecord(getAllData);
})
//领取方撤销操作
$("#getOperationBack").click(function(){
    if(getOperation.length === 0){
        layer.msg('已经是最初的样子了');
        return false;
    }
    let item = getOperation.pop();
    let o = {};
    for(let key in item){
        o[key] = getOperationRecord[key][getOperationRecord[key].length-2];
        // 将记录的最后一项推出
        debugger
        initForm(key,o[key]);
        getOperationRecord[key].pop();
    }
    setAllConfig(o);
})
// 领取方 保存操作(注意这个保存仅保存当前的ui配置)
$("#getSave").click(function(){
    // 从记录中提取最新的用户选择项
    let res = extractData(getOperationRecord);
    let changeRes = {
        receiver_ui_set:{
            activity_rule_list:{

            }
        }
    }
    leaveData(res,changeRes.receiver_ui_set.activity_rule_list);
    console.log(changeRes);
})
// 配置数据的key值和要操作的dom的id之前的对应关系
var idToDomMap = {
    my_background_color:'.my_background_color_target',
    my_title_editor_set_text:'#my_title_editor_set_target',
    my_title_editorfont_set_color:'#my_title_editor_set_target',
    my_subtitle_editor_set_text:'#my_subtitle_editor_set_text_target',
    my_subtitle_editorfont_set_color:'#my_subtitle_editor_set_text_target',
    my_shadow_opacity_slider:'#my_shadow_opacity_slider_target',
    my_module_shadow_color:'#my_shadow_opacity_slider_target',
    my_module_border_color:'#my_shadow_opacity_slider_target',
    my_module_color:'#my_shadow_opacity_slider_target',
    my_is_show_usecondition_select:'.my_is_show_usecondition_select_target',
    my_coupon_unit_mulcolor:'.my_coupon_unit_color_target',
    my_coupon_limit_color:'#my_coupon_limit_color_target',
    my_subcoupontitle_font_color:'#my_subcoupontitle_font_color_target',
    my_usecondition_subtext_font_color:'#my_subcoupontitle_font_color_target',
    my_usecondition_text_font_color:'#my_usecondition_text_font_color_target',
    my_coupon_border_color:'#my_coupon_border_color_target',

    friend_title_editor_set_text:'#friend_title_editor_set_text_target',
    friend_title_editorfont_set_color:'#friend_title_editor_set_text_target',
    friend_subtitle_editor_set_text:'#friend_subtitle_editor_set_text_target',
    friend_subtitle_editorfont_set_color:'#friend_subtitle_editor_set_text_target',
    friend_is_show_usecondition_select:'#friend_is_show_usecondition_select_target',
    friend_coupon_unit_mulcolor:'.friend_coupon_unit_mulcolor_target',
    friend_coupon_limit_color:'#friend_coupon_limit_color_target',
    friend_subcoupontitle_font_color:'#friend_subcoupontitle_font_color_target',
    friend_usecondition_text_font_color:'#friend_is_show_usecondition_select_target',
    friend_usecondition_subtext_font_color:'#friend_subcoupontitle_font_color_target',
    friend_coupon_border_color:'#friend_coupon_border_color_target',
    friend_coupon_border_color:'#friend_coupon_border_color_target',
    friend_module_color:'#friend_module_border_color_target',
    friend_module_border_color:'#friend_module_border_color_target',
    friend_module_shadow_color:'#friend_module_border_color_target',
    friend_shadow_opacity_slider:'#friend_module_border_color_target',

    invite_editor_set_text:"#invite_editor_set_text_target",
    invite_editor_set_color:"#invite_editor_set_text_target",
    invite_show_total_friends_radio:'#invite_show_total_friends_radio_target',
    invite_show_total_friends_color:'#invite_show_total_friends_radio_target',
    invite_module_color:'#invite_module_color_target',
    invite_module_border_color:'#invite_module_color_target',
    invite_module_shadow_color:'#invite_module_color_target',
    invite_module_shadow_opacity_slider:'#invite_module_color_target',

    activity_background_color:'#activity_background_color_target',
    activity_module_border_color:'#activity_background_color_target',
    activity_module_shadow_color:'#activity_background_color_target',
    activity_shadow_opacity_slider:'#activity_background_color_target',

    bottom_editor_title_text:'#bottom_editor_title_text_target',
    bottom_editor_set_color:'#bottom_editor_title_text_target',
    bottom_editor_set_background_color:'#bottom_editor_title_text_target',
    // 领取方
    you_background_color:'.you_background_color_target',
    you_title_editor_set_text:'#you_title_editor_set_text_target',
    you_title_editorfont_set_color:'#you_title_editor_set_text_target',
    you_subtitle_editor_set_text:'#you_subtitle_editor_set_text_target',
    you_subtitle_editorfont_set_color:'#you_subtitle_editor_set_text_target',
    you_is_show_usecondition_select:'.you_is_show_usecondition_select_target',
    you_coupon_unit_mulcolor:'.you_coupon_unit_color_target',
    you_coupon_limit_color:'#you_coupon_limit_color_target',
    you_subcoupontitle_font_color:'#you_subcoupontitle_font_color_target',
    you_usecondition_subtext_font_color:'#you_subcoupontitle_font_color_target',
    you_usecondition_text_font_color:'#you_usecondition_text_font_color_target',
    you_coupon_border_color:'#you_coupon_border_color_target',
    you_module_color:'#you_module_color_target',
    you_module_border_color:'#you_module_color_target',
    you_module_shadow_color:'#you_module_color_target',
    you_shadow_opacity_slider:'#you_module_color_target',

    activityto_background_color:"#activityto_background_color_target",
    activityto_module_border_color:"#activityto_background_color_target",
    activityto_module_shadow_color:"#activityto_background_color_target",
    activityto_shadow_opacity_slider:"#activityto_background_color_target",

    bottomto_editor_title_text:'#bottomto_editor_title_text_target',
    bottomto_editor_set_color:'#bottomto_editor_title_text_target',
    bottomto_editor_set_background_color:'#bottomto_editor_title_text_target',

};
// 配置数据的key值要操作的css样式
var idToStyleMap = {
    my_title_editorfont_set_color:'color',
    my_subtitle_editorfont_set_color:'color',
    my_module_shadow_color:'shadow',
    my_module_border_color:'border',
    my_module_color:'background',
    my_coupon_limit_color:'color',
    my_subcoupontitle_font_color:'color',
    my_usecondition_subtext_font_color:'background',
    my_usecondition_text_font_color:'color',
    my_coupon_border_color:'border',

    friend_title_editorfont_set_color:'color',
    friend_subtitle_editor_set_text:'color',
    friend_subtitle_editorfont_set_color:'color',
    friend_coupon_limit_color:'color',
    friend_subcoupontitle_font_color:'color',
    friend_usecondition_text_font_color:'color',
    friend_usecondition_subtext_font_color:'background',
    friend_coupon_border_color:'border',
    friend_coupon_border_color:'border',
    friend_module_color:'background',
    friend_module_border_color:'color',
    friend_module_shadow_color:'shadow',

    invite_editor_set_color:'color',
    invite_show_total_friends_color:'color',
    invite_module_color:'background',
    invite_module_border_color:'border',
    invite_module_shadow_color:'shadow',

    activity_background_color:'background',
    activity_module_border_color:'border',
    activity_module_shadow_color:'shadow',

    bottom_editor_set_color:'color',
    bottom_editor_set_background_color:'background',

    you_background_color:'background',
    you_title_editorfont_set_color:'color',
    you_subtitle_editorfont_set_color:'color',
    you_coupon_limit_color:'color',
    you_subcoupontitle_font_color:'color',
    you_usecondition_subtext_font_color:'background',
    you_usecondition_text_font_color:'color',
    you_coupon_border_color:'border',
    you_module_color:"background",
    you_module_border_color:"border",
    you_module_shadow_color:'shadow',

    activityto_background_color:'background',
    activityto_module_border_color:'border',
    activityto_module_shadow_color:'shadow',

    bottomto_editor_set_color:'color',
    bottomto_editor_set_background_color:'background',
    my_background_color:'background',
};
function returnDom(id){
    return idToDomMap[id];
}
function returnStyle(id){
    return idToStyleMap[id];
}
// 根据不同的key值产生相应的操作
function operationFun(id,val){
    // 获取id的后缀
    let suffix = id.slice(id.lastIndexOf('_')+1);
    switch(suffix){
        case 'text':
            disposeText(id,val);
            initForm(id,val);
        break;
        case 'color':
            disposeStyle(id,val);
        break;
        case 'mulcolor':
            $(returnDom(id)).each(function(){
                let type = $(this).data('mul');
                if(type === 'color'){
                    $(this).css('color',val);
                }else if(type === 'background'){
                    $(this).css('background',val);
                }
            })
        break;
    }     
}
// 处理后缀是text的情况
function disposeText(id,val){
    $(returnDom(id)).text(val);
}
// 处理后缀是color的情况
function disposeStyle(id,val){
    switch(returnStyle(id)){
        case 'color':
            $(returnDom(id)).css('color',val);
        break;
        case 'shadow':
            changeShow(id,val,'color');
        break;
        case 'border':
            $(returnDom(id)).css('border','1px solid '+val);
        break;
        case 'background':
            $(returnDom(id)).css('background',val);
        break;
    }
    
}
// 分享方配置数据
var setAllDatas = {
    my_background_color:'#fff',
    my_title_editor_set_text:'我的福利xx',
    my_title_editorfont_set_color:'#a00',
    my_subtitle_editor_set_text:'邀请新人好友首次下单签收即可获得',
    my_subtitle_editorfont_set_color:'#0a0',
    my_coupon_style_set_radio:0, // 简约版 还是 渐变版
    my_is_show_usecondition_select:0, // 0 是 1 否
    my_coupon_unit_mulcolor:'#1e9fff',
    my_coupon_limit_color:'#fff', // 优惠券额度单位标签字体颜色
    my_subcoupontitle_font_color:'#fff',
    my_usecondition_text_font_color:'#0a0',
    my_usecondition_subtext_font_color:'#1e9fff',
    my_coupon_border_color:'#aaa',
    my_module_color:'#fff',
    my_module_border_color:'#fff',
    my_module_shadow_color:'#aaa',
    my_shadow_opacity_slider:10,

    friend_background_color:'#666',
    friend_title_editor_set_text:'我的福利',
    friend_title_editorfont_set_color:'#a00', // 文案字体颜色
    friend_subtitle_editor_set_text:'邀请新人好友首次下单签收即可获得', // 副标题
    friend_subtitle_editorfont_set_color:'#0a0', // 副标题颜色
    friend_coupon_style_set_radio:0, // 简约版 还是 渐变版
    friend_is_show_usecondition_select:0, //优惠券模板 0 是 1 否
    friend_coupon_unit_mulcolor:'#1e9fff', // 券标题颜色
    friend_coupon_limit_color:'#fff',  // 单位标签字体
    friend_subcoupontitle_font_color:'#666', // 优惠券副标题
    friend_usecondition_text_font_color:'#666', // 核销门槛字体颜色
    friend_usecondition_subtext_font_color:'#fff', // 副券填充色
    friend_coupon_border_color:'#ccc', // 优惠券边框
    friend_module_color:'#fff', // 模块背景
    friend_module_border_color:'#fff', // 模块边框
    friend_module_shadow_color:'#aaa', // 模块阴影颜色
    friend_shadow_opacity_slider:10,  // 模块阴影透明度

    invite_editor_set_text:"邀请好友", // 标题文案
    invite_editor_set_color:"#666", // 文案颜色
    invite_show_total_friends_radio:"0", // 是否展示邀请好友总数
    invite_show_total_friends_color:"#666", // 好友总数的字体颜色
    invite_module_color:"#fff", // 模块背景色
    invite_module_border_color:"#fff", // 模块边框颜色
    invite_module_shadow_color:"#aaa", // 模块阴影颜色
    invite_module_shadow_opacity_slider:10,  // 模块阴影透明度

    activity_activity_rule_html:"<h2>哈哈</h2>",
    activity_background_color:"#fff", // 模块背景色
    activity_module_border_color:"#fff", // 模块边框颜色
    activity_module_shadow_color:"#aaa", // 模块阴影色
    activity_shadow_opacity_slider:"10", // 模块阴影透明度

    bottom_editor_title_text:'立即邀请', // 底部按钮文本
    bottom_editor_set_color:"#fff", // 按钮颜色
    bottom_editor_set_background_color:'#1e9fff', // 按钮背景色
}
// 领取发方配置数据
var getAllDatas = {
    you_background_color:'#666',
    you_title_editor_set_text:'我的福利s',
    you_title_editorfont_set_color:'#a00',
    you_subtitle_editor_set_text:'邀请新人好友首次下单签收即可获得',
    you_subtitle_editorfont_set_color:'#0a0',
    you_coupon_style_set_radio:1, // 福利券 0 简约版 1 渐变版
    you_is_show_usecondition_select:0, // 是否显示核销门槛 0 显示 1 不显示
    you_coupon_unit_mulcolor:'#00a',//券名称、券额度字体、单位标签 填充颜色
    you_coupon_limit_color:'#0a0',//优惠券额度单位标签字体颜色
    you_subcoupontitle_font_color:'#0a0',//优惠券副标题字体颜色
    you_usecondition_subtext_font_color:'#0a0',//核销门店副券填充颜色
    you_usecondition_text_font_color:'#0a0',//核销门槛字体颜色
    you_coupon_border_color:'#0a0', // 优惠券边框
    you_module_color:'#00a',
    you_module_border_color:'#a00',
    you_module_shadow_color:'#a00',
    you_shadow_opacity_slider:30,

    activityto_activityto_rule_html:"<h2>哈哈</h2>",
    activityto_background_color:"#0ca",
    activityto_module_border_color:"#00a",
    activityto_module_shadow_color:"#00a",
    activityto_shadow_opacity_slider:"70",

    bottomto_editor_title_text:'gge',
    bottomto_editor_set_color:"#1e9fff",
    bottomto_editor_set_background_color:'#4a1',
}

// 整体执行
function setAllConfig(obj){
    for(let key in obj){
        if(key.indexOf('_color') !== -1 || key.indexOf('_mulcolor') !== -1){
            colorPickers(key,obj);
            operationFun(key,obj[key])
        }else if(key.indexOf('_slider') !== -1){
            sliderRender(key,obj[key])
            changeShow(key,obj[key],'dim')
        }else if(key.indexOf('_radio') !== -1){
            radioBInd(key,obj[key])
        }else if(key.indexOf('_text') !== -1){
            operationFun(key,obj[key])
        }else if(key.indexOf('_select') !== -1){
            selectBind(key,obj[key]);
        }else if(key.indexOf('_html') !== -1){
            if(key.indexOf('activity_') !== -1){
                editor.html(obj[key]);
                $("#activity_activityto_rule_html").html(obj[key]);
            }else if(key.indexOf('activityto_') !== -1){
                getEditor.html(obj[key]);
                $("#activityto_activityto_rule_html_target").html(obj[key]);
            }
        }
    }
}

// 渲染颜色选择器方法
function colorPickers(key,obj){
        colorpicker.render({
            elem: '#'+key
            ,color: obj[key]
            ,done: function(color){
                // 在相关的地方把修改后的值改掉
                obj[key] = color;
                // 记录当前操作
                addUserOperation(key,obj[key]);
                // 将改变的值作用到相应dom
                operationFun(key,color);
            }
        });
}
// 如果是 text，radio，select后缀，要使用form的进行重新赋值
function initForm(id,val){
    let suffix = id.slice(id.lastIndexOf('_')+1);
    switch(suffix){
        case 'text'  :
        case 'radio' :
        case 'select':
            form.val('global-form',{
                [id]:val
            })
        break;
        case 'html' :
            if(id.indexOf('activity_') !== -1){
                editor.html(val);
            }else if(id.indexOf('activityto_') !== -1){
                getEditor.html(val);
            }
        break;
    }
}
// 改变shadow
function changeShow(key,value,type){
    var shadow = $(returnDom(key)).css('box-shadow');
    if(type === 'dim' && shadow){
        var color = shadow.slice(0,shadow.indexOf(')')+1);
        $(returnDom(key)).css('box-shadow','0px 0px '+value+'px '+color);
    }else if(type== 'color' && shadow){
        var s = value+' '+shadow.slice(shadow.indexOf(')')+2);
        $(returnDom(key)).css('box-shadow',s);
    }
}
// 渲染滑块
var timer;
function sliderRender(key,value,min=0,max=50){
    slider.render({
        elem:"#"+key
        ,tips: false //关闭默认提示层
        ,min:min
        ,max:max
        ,input:true
        ,step:1
        ,value:value
        ,change: function(value){
            // 增加操作记录(因为滑动条触发太过密集，增加个防抖加以限制)
            clearTimeout(timer);
            timer = setTimeout(function(){
                console.log('slider')
                addUserOperation(key,value);
            },200)
            // 操作相应的dom
            changeShow(key,value,'dim')
        }
    });
}
// radio事件
function radioBInd(id,value){
    initForm(id,value);
    // 给radio绑定相应的事件
    if(id === 'my_coupon_style_set_radio'){
        function radio_a(v){
            if(v == 0){
                $(".version-simple").show(300);
                $(".version-gradient").hide(300);
            }else{
                $(".version-simple").hide(300);
                $(".version-gradient").show(300);
            }
        }
        radio_a(value);
        form.on('radio(my_coupon_style_set_radio)',function(r){
            radio_a(r.value);
            addUserOperation(id,r.value);
        })
    }else if(id === 'friend_coupon_style_set_radio'){
        function radio_b(v){
            if(v == 0){
                $(".friend-version-simple").show(300);
                $(".friend-version-gradient").hide(300);
            }else{
                $(".friend-version-simple").hide(300);
                $(".friend-version-gradient").show(300);
            } 
        }
        radio_b(value);
        form.on('radio(friend_coupon_style_set_radio)',function(r){
            radio_b(r.value);
        })
    }else if(id === 'invite_show_total_friends_radio'){
        function select_three(v){
            if(v == 0){
                $(returnDom('invite_show_total_friends_radio')).show();
            }else{
                $(returnDom('invite_show_total_friends_radio')).hide();
            }
        }
        select_three(value);
        form.on('radio(invite_show_total_friends_radio)',function(r){
            select_three(r.value);
            addUserOperation(id,r.value);
        })
    }else if(id === 'you_coupon_style_set_radio'){
        function select_four(v){
            if(v == 0){
                $(".you-version-simple").show(300);
                $(".you-version-gradient").hide(300);
            }else{
                $(".you-version-simple").hide(300);
                $(".you-version-gradient").show(300);
            }
        }
        select_four(value);
        form.on('radio(you_coupon_style_set_radio)',function(r){
            select_four(r.value);
            addUserOperation(id,r.value);
        })
    }
}
// select 事件
function selectBind(id,value){
    if(id === "my_is_show_usecondition_select"){
        initForm(id,value);
        function select_one(v){
            if(v == 0){
                $(returnDom('my_is_show_usecondition_select')).show();
            }else{
                $(returnDom('my_is_show_usecondition_select')).hide();
            }
        }
        select_one(value);
        form.on('select(my_is_show_usecondition_select)',function(r){
            select_one(r.value);
            addUserOperation(id,r.value);
        })
    }
    if(id === 'friend_is_show_usecondition_select'){
        function select_two(v){
            if(v == 0){
                $(returnDom('friend_is_show_usecondition_select')).show();
            }else{
                $(returnDom('friend_is_show_usecondition_select')).hide();
            }
        }
        select_two(value);
        form.on('select(friend_is_show_usecondition_select)',function(r){
            select_two(r.value);
            addUserOperation(id,r.value);
        })
    }
    if(id === 'you_is_show_usecondition_select'){
        debugger
        function select_three(v){
            if(v == 0){
                $(returnDom('you_is_show_usecondition_select')).show();
            }else{
                $(returnDom('you_is_show_usecondition_select')).hide();
            }
        }
        select_three(value);
        form.on('select(you_is_show_usecondition_select)',function(r){
            select_three(r.value);
            addUserOperation(id,r.value);
        })
    }
}

 function renderTable(obj){
     var  obj = typeof obj === 'object' ? obj : {};
     var o =table.render({
         elem:obj.elem,
         data:obj.data,
         cols:obj.cols
     })
     return o;
 }
 // 控制元素显示还是隐藏
 function controlShow(list,target){
     list.forEach(item=>{
         if(item !== target){
             $(item).hide(400);
         }else{
             $(item).show(400)
         }
     })
 }

 // 活动生效时段

  /*可使用时段*/
  function timeAdd(){
    $('.datetime').each(function() {
        laydate.render({
            elem : this,
            trigger : 'click'
            ,type: 'time'
            ,range: false
            ,ready: function(date) {
                var html = '';

                html ='<input type="checkbox" value="1" name="is_next_day" title="跨日营业" ' +
                    'checked lay-skin="primary">'+'跨日营业';

                $('.layui-laydate-footer').append(html)
            }
        });
    });
}
//给新增按钮添加点击事件
$('.add-btn-js').click(function(){
    let html2 = `
    <div class="layui-form-item">
                <label class="layui-form-label">活动生效时段</label>
                <div class="layui-input-inline">
                  <input type="text" name="time1"  placeholder="--:--" autocomplete="off" class="layui-input datetime">
                </div>
                <div class="layui-form-mid">---</div>
                <div class="layui-input-inline">
                  <input type="text" name="time1"  placeholder="--:--" autocomplete="off" class="layui-input datetime">
                </div>
                <div class="layui-input-inline" style="width:80px;"><button type="button" class="layui-btn layui-btn-danger add-delete-js"><i
                      class="layui-icon">&#xe640;</i>删除</button></div>
              </div>
    `
    $(".active-effect").append(html2)
    // form.render();
    timeAdd()
})
// 给新增加的删除按钮增加事件
$("body").on("click", ".add-delete-js",function(){
    $(this).parents(".layui-form-item").remove()
});
 
 //************* */每月循环日期日期选择器
let initData=[]

//最终选择的日期数组
function lastData() {
    let lastdata=[]
    initData.forEach(function (item,index) {
        if(item.check){
            lastdata.push(item.value)
        }
    })
    return lastdata;
}

for(let i=1;i<=31;i++){
    initData.push({check:false,value:i})
}
//点击选择
$('.custom-date ul').on('click','li',function () {
    if($(this).find('a').hasClass('active')){
        $(this).find('a').removeClass('active')
    }else{
        $(this).find('a').addClass('active')
    }
    $('.custom-date ul li a').each(function (i,k) {
            initData.forEach(function (item,index) {
                if(item.value==$(k).text()){
                    if($(k).hasClass("active")){
                       item.check=true
                    }else{
                        item.check=false
                    }
                }
            })
    })
})
// 删除
$("body").on("click", ".loop-date .choose-box .choose-result",function(){
    let val=$(this).find('.text').text()
    initData.forEach(function (item,index) {
         if(item.value==val){
              item.check=false
         }
    })
    $(this).remove()

});
//显示日期选择
function dateshow() {
    $('.custom-date ul').empty()
    initData.forEach(function(item, index,) {
        if(item.check){
          $('.custom-date ul').append('<li> <a class="active">'+item.value+'</a> </li>')
        }else{
          $('.custom-date ul').append('<li> <a>'+item.value+'</a> </li>')
        }
    })
    $('.custom-date').show()
}
//确定选择
function selectRole() {
    $('.loop-date .choose-box .choose-result').remove()

    $('.custom-date ul li a').each(function (i,k) {
        if($(k).hasClass("active")){
            initData.forEach(function (item,index) {
               if(item.value==$(k).text()){
                   item.check=true
               }
            })
        }

    })
    initData.forEach(function (item,index) {
        if(item.check){
           $('.loop-date .choose-box').append('<div class="choose-result"><span class="text">'+item.value+'</span><i class="layui-icon" style="color: #fff;">&#x1006;</i></div>')
        }
    })
    $('.custom-date').hide()
}
//取消选择
function canelChoose() {
    $('.custom-date').hide()
}
//************* 每月循环日期日期选择器end*/
//分享者领取礼包条件 左侧的勾选按钮事件
$(".itemLeft").click(function(){
    // 找到当前对应的选项 是否含radio选项
    var count = $(this).parent().find('input[type=radio]').length;
    var $icon = $(this).find('.iconfont');
    if($icon.hasClass('active')){
        $icon.removeClass('active');
        if(count > 0){
            $(this).parent().find('input[type=radio]').prop('disabled',true);
            form.render('radio');
        }
        if($(this).data('fun') === 'share-obj-order'){
            $(".show-share-person-js").hide(100);
        }

    }else{
        $icon.addClass('active');
        if(count > 0){
            $(this).parent().find('input[type=radio]').prop('disabled',false);
            form.render('radio');
        }
        if($(this).data('fun') === 'share-obj-order'){
            $(".show-share-person-js").show(100,function(){
                // 显示包含指定商品的数据表格
                handle = renderTable({
                    elem:'#includeGoods',
                    data:includeGoodsData,
                    cols:includeGoodsCols
                })
                table.on('tool(includeGoods)',function(r){
                    switch(r.event){
                        case 'detail':
                            // 跳转到详情页

                        break;
                        case 'delete':
                            // 删除当前项
                            includeGoodsData.splice($(r.tr).data('index'),1);
                            renderTable({
                                elem:'#includeGoods',
                                data:includeGoodsData,
                                cols:includeGoodsCols
                            })
                        break;
                    }
                })
            });
        }
    }
})


